package com.ai.wx.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.core.cache.AICacheManager;
import com.ai.core.constant.GlobalConstant;
import com.ai.core.dao.BaseDaoI;
import com.ai.wx.entity.Product;
import com.ai.wx.entity.ProductPromotion;
import com.ai.wx.pojo.PproductPromotion;
import com.ai.wx.service.ProductPromotionService;

@Service
public class ProductPromotionServiceImpl implements ProductPromotionService {
	@Autowired
	private BaseDaoI<ProductPromotion> productPromotionDao;

	@Override
	public List<PproductPromotion> getPromoList() {
		AICacheManager aiCacheManager = AICacheManager.getInstance();
		Map map = aiCacheManager.getMap(GlobalConstant.CACHE_PRODUCT_MAP);
		List<Product> productList = (List<Product>) map.get(GlobalConstant.OPER_ID_ALL);

		List<PproductPromotion> promoList = new ArrayList<PproductPromotion>();
		for (Product p : productList) {
			PproductPromotion promo = new PproductPromotion();
			promo.setProductId(p.getProductId());
			promo.setProductName(p.getProductName());
			ProductPromotion highPro = getPromoByProIdAndPromoRate(p.getProductId(), GlobalConstant.PROM_CODE_HIGH);
			ProductPromotion midPro = getPromoByProIdAndPromoRate(p.getProductId(), GlobalConstant.PROM_CODE_MID);
			ProductPromotion lowPro = getPromoByProIdAndPromoRate(p.getProductId(), GlobalConstant.PROM_CODE_LOW);

			if (highPro != null) {
				promo.setHigDiscount(highPro.getDbDiscount());
				promo.setHigBrokerage(highPro.getDbBrokerage());
			}
			if (midPro != null) {
				promo.setMidDiscount(midPro.getDbDiscount());
				promo.setMidBrokerage(midPro.getDbBrokerage());
			}
			if (lowPro != null) {
				promo.setLowDiscount(lowPro.getDbDiscount());
				promo.setLowBrokerage(lowPro.getDbBrokerage());
			}

			promoList.add(promo);
		}
		return promoList;
	}

	private ProductPromotion getPromoByProIdAndPromoRate(String productId, int promotionRate) {
		String sql = "select p.product_id as productId,p.discount as discount,p.brokerage as brokerage,p.promotion_rate as promotionRate,p.state as state from product_promotion p where p.state=1 and p.product_id=:productId and p.promotion_rate=:promotionRate";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("productId", productId);
		params.put("promotionRate", promotionRate);
		List<ProductPromotion> pl = productPromotionDao.findEntityBySql(sql, params, ProductPromotion.class);
		if (pl != null && pl.size() > 0) {
			return pl.get(0);
		}
		return null;
	}

}
